#include <iostream>
#include <sys/types.h>         
#include <sys/socket.h>
#include "Log.hpp"
#include <string.h>
#include <netinet/in.h>
#include <pthread.h>
#include "InetAddr.hpp"
#include <string>

const static int defaultsockfd = -1;
const static int gbacklog = 16;//最大监听数量

class TcpServer;

//作为参数传入线程中
class ThreadData
{
    public:
    ThreadData(int sock,const InetAddr addr,TcpServer* self)
    :_sock(sock)
    ,_addr(addr)
    ,_self(self)
    {}

    int _sock;
    InetAddr _addr;
    TcpServer* _self;//这个可以访问类的函数
};

class TcpServer
{
public:
    TcpServer(int port)
    :_port(port)
    ,_isrunning(false)
    ,_listensock(defaultsockfd)
    {}
    
    void InitServer()
    {
        //1.创建流式套接字
        _listensock = socket(AF_INET,SOCK_STREAM,0);
        if(_listensock<0)
        {

            Log(FATAL,"socket error\n");
            exit(-1);
        }
        Log(DEBUG,"socket create success,sockfd:%d\n",_listensock);

        //2.bind绑定
        struct sockaddr_in local;
        memset(&local,0,sizeof(local));
        local.sin_family = AF_INET;
        //不管数据是从哪个网卡过来的，只要是绑定的端口号过来的数据，都可以接收到。
        local.sin_addr.s_addr =  INADDR_ANY;
        local.sin_port = htons(_port);
        int n = bind(_listensock,(struct sockaddr*)&local,sizeof(local));
        if(n<0)
        {
            Log(FATAL,"bind error\n");
            exit(-2);
        }
        Log(DEBUG,"bind success,sockfd:%d\n",_listensock);

        //3.listen tcp面向连接，再通讯之前需要先建立连接
        n = listen(_listensock,gbacklog);
        if(n<0)
        {
            Log(FATAL,"listen error\n");
            exit(-3);
        }
        Log(DEBUG,"liseten success,sockfd:%d\n",_listensock);
    }

    void Service(int sockfd,InetAddr clientaddr)
    {
        Log(DEBUG,"get a new link,info:%s,%d,fd:%d",clientaddr.Ip().c_str(),clientaddr.Port(),sockfd);
        std::string clientaddrstring = "["+clientaddr.Ip()+":"+std::to_string(clientaddr.Port())+"]";
        while(1)
        {
            char buffer[1024];
            //面向字节流，可以直接使用read和write读写
            size_t n = read(sockfd,buffer,sizeof(buffer));
            if(n>0)
            {
                buffer[n] = 0;
                std::cout<<clientaddrstring<<buffer<<std::endl;

                std::string echo_string = "[server echo]#"+string(buffer);
                write(sockfd,echo_string.c_str(),echo_string.size()); 
            }
            else if(n==0)
            {
                //client写端关闭
                Log(INFO,"%s quit\n",clientaddrstring.c_str());
                break;
            }
            else
            {
                Log(ERROR, "read error\n", clientaddrstring.c_str());
                break;
            }
        }
    }

    static void* HandlerSock(void* args)
    {
        pthread_detach(pthread_self());//获取调用线程ID，并且detach
        ThreadData* td = static_cast<ThreadData*>(args);
        td->_self->Service(td->_sock,td->_addr);//调用服务函数
        delete td;
        return nullptr;
    }


    void Loop()
    {
        _isrunning = true;
        //4.接收连接
        while(_isrunning)
        {
            struct sockaddr_in peer;
            socklen_t len = sizeof(peer);
            int sockfd = accept(_listensock,(struct sockaddr*)&peer,&len);
            if(sockfd<0)
            {
                Log(WARNING,"accept error\n");
                continue;
                //如果得到的fd<0，就继续接受连接
            }
            Log(DEBUG,"accept success,sockfd:%d\n",_listensock);

            //创建线程，把收到的信息返回
            pthread_t t;
            ThreadData* ptr = new ThreadData(sockfd,InetAddr(peer),this);
            pthread_create(&t,nullptr,HandlerSock,ptr);//在函数中把线程分离
        }
        _isrunning = false;

    }


    ~TcpServer()
    {
        if(_listensock!=defaultsockfd)
            close(_listensock);
    }

private:
    int _listensock;
    int _port;
    bool _isrunning;

};